import * as loginAPI from "@/api/login";
import * as mutationTypes from "@/store/mutation-types";
import { welcome } from "@/utils/util";
import { queryPermissionsByUser } from '@/api/api';
import { getAction } from '@/api/manage';
import * as storage from '@/utils/storage';

const user = {
    state: {
        token: '',
        username: '',
        realname: '',
        welcome: '',
        avatar: '',
        permissionList: [],
        info: {}
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, {
            username,
            realname,
            welcome
        }) => {
            state.username = username
            state.realname = realname
            state.welcome = welcome
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_PERMISSIONLIST: (state, permissionList) => {
            state.permissionList = permissionList
        },
        SET_INFO: (state, info) => {
            state.info = info
        },
    },

    actions: {
        // CAS验证登录
        ValidateLogin({
            commit
        }, userInfo) {
            return new Promise((resolve, reject) => {
                getAction("/cas/client/validateLogin", userInfo).then(response => {
                    console.log("----cas 登录--------", response);
                    if (response.success) {
                        const result = response.result
                        const userInfo = result.userInfo
                        Vue.ls.set(mutationTypes.ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
                        Vue.ls.set(mutationTypes.USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
                        Vue.ls.set(mutationTypes.USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
                        commit('SET_TOKEN', result.token)
                        commit('SET_INFO', userInfo)
                        commit('SET_NAME', {
                            username: userInfo.username,
                            realname: userInfo.realname,
                            welcome: welcome()
                        })
                        commit('SET_AVATAR', userInfo.avatar)
                        resolve(response)
                    } else {
                        resolve(response)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登录
        Login({
            commit
        }, userInfo) {
            return new Promise((resolve, reject) => {
                loginAPI.login(userInfo).then(response => {
                    if (response.code == '200') {
                        const result = response.result
                        const userInfo = result.userInfo
                        Vue.ls.set(mutationTypes.ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
                        Vue.ls.set(mutationTypes.USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
                        Vue.ls.set(mutationTypes.USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
                        commit('SET_TOKEN', result.token)
                        commit('SET_INFO', userInfo)
                        commit('SET_NAME', {
                            username: userInfo.username,
                            realname: userInfo.realname,
                            welcome: welcome()
                        })
                        commit('SET_AVATAR', userInfo.avatar)
                        resolve(response)
                    } else {
                        reject(response)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //手机号登录
        PhoneLogin({
            commit
        }, userInfo) {
            return new Promise((resolve, reject) => {
                loginAPI.phoneLogin(userInfo).then(response => {
                    if (response.code == '200') {
                        const result = response.result
                        const userInfo = result.userInfo
                        Vue.ls.set(mutationTypes.ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
                        Vue.ls.set(mutationTypes.USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
                        Vue.ls.set(mutationTypes.USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
                        commit('SET_TOKEN', result.token)
                        commit('SET_INFO', userInfo)
                        commit('SET_NAME', {
                            username: userInfo.username,
                            realname: userInfo.realname,
                            welcome: welcome()
                        })
                        commit('SET_AVATAR', userInfo.avatar)
                        resolve(response)
                    } else {
                        reject(response)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        GetPermissionList({
            commit
        }) {
            var that = this;
            var browserName = window.navigator.userAgent.toLowerCase().includes('firefox') ? 'firefox' : 'chrome';
            //清空Token信息，并返回登录页面
            var goBackLoginPage = () => {
                if (browserName !== 'firefox') {
                    //清空缓存，一般是因为浏览器token有效，但是远程服务器token失效，清空token信息即可
                    storage.clearStore('pro__Access-Token');
                    storage.clearDB('pro__Access-Token');
                    console.log('token reject by remote server , probally caused by token invalid... ');
                    window.location.href = `/user/login`;
                }
            }

            return new Promise((resolve, reject) => {
                let v_token = Vue.ls.get(mutationTypes.ACCESS_TOKEN);
                let params = {
                    token: v_token
                };
                queryPermissionsByUser(params).then(response => {
                    const menuData = response.result.menu;
                    const authData = response.result.auth;
                    const allAuthData = response.result.allAuth;
                    sessionStorage.setItem(mutationTypes.USER_AUTH, JSON.stringify(authData));
                    sessionStorage.setItem(mutationTypes.SYS_BUTTON_AUTH, JSON.stringify(allAuthData));
                    if (menuData && menuData.length > 0) {
                        commit('SET_PERMISSIONLIST', menuData);
                    } else {
                        goBackLoginPage();
                        reject('getPermissionList: permissions must be a non-null array !');
                    }
                    resolve(response);
                }).catch(error => {
                    goBackLoginPage();
                    reject(error);
                })
            })
        },

        // 登出
        Logout({
            commit,
            state
        }) {
            return new Promise((resolve) => {
                let logoutToken = state.token;
                commit('SET_TOKEN', '')
                commit('SET_PERMISSIONLIST', [])
                Vue.ls.remove(mutationTypes.ACCESS_TOKEN)
                loginAPI.logout(logoutToken).then(() => {
                    resolve()
                }).catch(() => {
                    resolve()
                })
            })
        },

    }
}

export default user